import 'dart:math';

import 'package:flutter/cupertino.dart';

// 水纹涟漪
class XinDongAnimationWaterRipple extends StatefulWidget {
  final int count;
  final Color color;
  final double minRadius; // 最小圆弧半径，默认0
  final double maxRadius; // 最大圆弧半径，默认100

  const XinDongAnimationWaterRipple(
      {Key? key, this.count = 3, this.color = const Color(0xFF0080ff), this.minRadius = 0, this.maxRadius = 100})
      : super(key: key);

  @override
  State<XinDongAnimationWaterRipple> createState() => _XinDongAnimationWaterRippleState();
}

class _XinDongAnimationWaterRippleState extends State<XinDongAnimationWaterRipple> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 888))..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(
          painter: WaterRipplePainter(
            widget.count,
            widget.color,
            _controller.value,
            widget.minRadius,
            widget.maxRadius,
          ),
        );
      },
    );
  }
}

class WaterRipplePainter extends CustomPainter {
  final int count;
  final Color color;
  final double progress;
  final double minRadius; // 最小圆弧半径，默认0
  final double maxRadius; // 最大圆弧半径，默认100

  // Paint _paint = Paint()..style = PaintingStyle.fill;
  final Paint _paint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 1.5;

  WaterRipplePainter(this.count, this.color, this.progress, this.minRadius, this.maxRadius);

  @override
  void paint(Canvas canvas, Size size) {
    // double radius = min(size.width / 2, size.height / 2);
    double space = (maxRadius - minRadius).abs() / max(count - 1, 1);
    for (int i = 0; i < count; i++) {
      final double opacity = (1.0 - ((i + progress) / (count)));
      _paint.color = color.withOpacity(opacity);
      // double _radius = min(radius * ((i + progress) / (count + 1)) + minRadius, this.maxRadius);
      double radius = min((space * (i + progress)) + minRadius, maxRadius);
      canvas.drawCircle(Offset(size.width / 2, size.height / 2), radius, _paint);
    }
  }

  // @override
  // void paint(Canvas canvas, Size size) {
  //   double space = (this.maxRadius - this.minRadius).abs() / count;
  //   for (int i = 0; i < count ; i++) {
  //     final double opacity = (1.0 - ((i + progress) / (count)));
  //     _paint..color = color.withOpacity(opacity);
  //     double _radius = (space * (i + progress)) + minRadius;
  //     canvas.drawCircle(Offset(size.width / 2, size.height / 2), _radius, _paint);
  //   }
  // }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
